//
//  S1mpl3AlbumViewController.m
//  沙哈拉FM
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 S1mpl3. All rights reserved.
//

#import "S1mpl3AlbumViewController.h"
#import "TwoToOne.h"
#import "FitHeader.h"
#import "MJRefresh.h"
#import "TabBarController.h"
#import "S1mpl3AlbumTableViewCell.h"
#import "S1mpl3TableViewHeadView.h"
#import "S1mpl3HeadView.h"
#import "UIImage+GaussianBlur.h"
#import "S1mpl3MoreInfoViewController.h"
#import "S1mpl3HeadInfoViewController.h"
#import "S1mpl3AboutViewController.h"
#import "LZPlayViewController.h"
#import "LZBillboardModel.h"
#import "UIImage+GIF.h"
#import "CoreDataManager.h"


#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"

@interface S1mpl3AlbumViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSourceArray;
@property(nonatomic,strong)NSString *totalString;
@property(nonatomic,strong)NSMutableDictionary *albumDic;
@property(nonatomic,strong)S1mpl3HeadView *s1mpl3HeadView;
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UILabel *s1mpl3Label;
@property(nonatomic,assign)NSInteger s1mpl3Flag;
@property(nonatomic,assign)NSInteger num;
@property(nonatomic,strong)NSString *str;
@property(nonatomic, strong)NSMutableArray *headViewsArray;

@property(nonatomic,strong)CoreDataManager *manager;

@property(nonatomic, strong)NSMutableArray *LZarray;
@property(nonatomic, strong)MBProgressHUD *progressView;
@end

@implementation S1mpl3AlbumViewController

-(void)getData{
    [TwoToOne getDataByString:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?albumId=%@&isAsc=true&device=android&pageSize=20", _albumId, _page, _albumId] BodyString:nil WithDataBlock:^(id data) {
//        NSLog(@"%@", [[data objectForKey:@"tracks"] objectForKey:@"list"]);
//        NSLog(@"%@", [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?albumId=%@&isAsc=true&device=android&pageSize=20", _albumId, _page, _albumId]);
        _num = 1;
        _albumDic = [data objectForKey:@"album"];
        _s1mpl3HeadView.dataSourceDic = [data objectForKey:@"album"];
        _imageView.image = [UIImage imageWithBlurImage:_s1mpl3HeadView.backImageView.image intputRadius:30];
        _totalString = [[data objectForKey:@"album"] objectForKey:@"tracks"];
        if ([[[data objectForKey:@"tracks"] objectForKey:@"list"]count] == 0) {
            [_tableView.mj_footer endRefreshing];
            _tableView.mj_footer.state = MJRefreshStateNoMoreData;
            return ;
        }
     
        for (NSDictionary *dic in [[data objectForKey:@"tracks"] objectForKey:@"list"]) {
            LZBillboardModel *model = [[LZBillboardModel alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            [_LZarray addObject:model];
            [_dataSourceArray addObject:dic];
        }
        [_tableView reloadData];
//        [_tableView.header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        [_progressView removeFromSuperview];
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [[TabBarController shareInstance] remainButtonOfPlay:YES];
    [TabBarController shareInstance].myView.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackTranslucent];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName]];
//    self.navigationController.navigationBar.hidden = YES;
    //查询
    NSArray *array = [NSMutableArray array];
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Focus"];
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", @"一菲"];
    //    [fetchRequest setPredicate:predicate];
    //    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
    //    [fetchRequest setSortDescriptors:@[sortDescriptor]];
    array = [_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    _str = [NSString stringWithFormat:@"%@", _moreRecommend.ID];
    for (Focus *s in array) {
        if (_recommend == nil) {
            _str = [NSString stringWithFormat:@"%@", _focus.iD];
        }
        if ([s.iD isEqualToString:_str]) {
            _s1mpl3HeadView.loveLabel.text = @"已收藏";
            return;
        }
    }
//    _s1mpl3HeadView.loveLabel.text = @"收藏";
}

-(void)viewWillDisappear:(BOOL)animated
{
    [[TabBarController shareInstance] remainButtonOfPlay:NO];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackTranslucent];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName]];
}

-(void)loadView{
    [super loadView];
    _manager = [CoreDataManager shareManager];
    _page = 1;
    self.dataSourceArray = [NSMutableArray array];
    self.albumDic = [NSMutableDictionary dictionary];
    _LZarray = [NSMutableArray array];
    
    [self getData];
    _s1mpl3HeadView = [[S1mpl3HeadView alloc] initWithFrame:CGRectMake(0, -50 * FITHeight, self.view.frame.size.width, 250 * FITHeight)];
    
    _s1mpl3HeadView.aboutImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *aboutTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(aboutTapAction)];
    [_s1mpl3HeadView.aboutImageView addGestureRecognizer:aboutTap];
    
    _s1mpl3HeadView.aboutLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *aboutTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(aboutTapAction)];
    [_s1mpl3HeadView.aboutLabel addGestureRecognizer:aboutTap1];
    
    
    _s1mpl3HeadView.moreImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *moreTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreTapAction)];
    [_s1mpl3HeadView.moreImageView addGestureRecognizer:moreTap];
    
    _s1mpl3HeadView.headImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *headTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headTapAction)];
    [_s1mpl3HeadView.headImageView addGestureRecognizer:headTap];
    
    _s1mpl3HeadView.logoLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *headTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headTapAction)];
    [_s1mpl3HeadView.logoLabel addGestureRecognizer:headTap1];
    
    
    _s1mpl3HeadView.loveImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *loveTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loveTapAction)];
    [_s1mpl3HeadView.loveImageView addGestureRecognizer:loveTap];
    
    _s1mpl3HeadView.loveLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *loveTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loveTapAction)];
    [_s1mpl3HeadView.loveLabel addGestureRecognizer:loveTap1];
    
    
    _imageView = [[UIImageView alloc] initWithFrame:_s1mpl3HeadView.backImageView.frame];
    _imageView.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -50 * FITHeight, self.view.frame.size.width, self.view.frame.size.height + 64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _s1mpl3HeadView.nav = self.navigationController;
    _tableView.tableHeaderView = _s1mpl3HeadView;
    [self.view addSubview:_tableView];
    
    
//    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [_dataSourceArray removeAllObjects];
//        _page = 1;
//        [self getData];
//    }];
    
    
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    [[[_progressView subviews]firstObject] removeFromSuperview];
    [[[_progressView subviews] objectAtIndex:1] removeFromSuperview];
    [_progressView setMode:0];
    [_progressView show:YES];
    NSString  *name = @"RED.gif";
    _progressView.color = [UIColor clearColor];
    NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(-70 * FITWidth, -80 * FITHeight, 140 * FITWidth, 100 * FITHeight)];
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = 10;
    imageView.opaque = NO;
    
    [[[[[_progressView subviews] lastObject] subviews] firstObject] removeFromSuperview];
    
    imageView.image = [UIImage sd_animatedGIFWithData:imageData];
    [[[_progressView subviews] lastObject] addSubview:imageView];    [self.view addSubview:_progressView];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getData];
    }];

}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"S1mpl3透明图"] forBarMetrics:UIBarMetricsDefault];
//    self.title = _myTitle;
    _headViewsArray = [NSMutableArray array];
    _s1mpl3Label = [[UILabel alloc] init];
    _s1mpl3Label.font = [UIFont systemFontOfSize:16];
//    _s1mpl3Label.backgroundColor = [UIColor orangeColor];
    CGRect rect = [_myTitle boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 49) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:16] forKey:NSFontAttributeName]context:nil];
    _s1mpl3Label.frame = CGRectMake(0, 0, ceill(rect.size.width + 1), 49);
    
    _s1mpl3Label.text = _myTitle;
    _s1mpl3Label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = _s1mpl3Label;
    
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 / 10.0 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
//     Do any additional setup after loading the view.
}

#pragma mark--定时器
-(void)timeAction{
 
    if (_s1mpl3Flag == 0) {
            _s1mpl3Label.frame = CGRectMake(_s1mpl3Label.frame.origin.x - 1, _s1mpl3Label.frame.origin.y, _s1mpl3Label.frame.size.width, _s1mpl3Label.frame.size.height);
            if (_s1mpl3Label.frame.origin.x < 20 ) {
                _s1mpl3Flag = 1;
            }
        }else if(_s1mpl3Flag == 1 ){
                _s1mpl3Label.frame = CGRectMake(_s1mpl3Label.frame.origin.x + 1, _s1mpl3Label.frame.origin.y, _s1mpl3Label.frame.size.width, _s1mpl3Label.frame.size.height);
            if (_s1mpl3Label.frame.origin.x == 275 * FITHeight) {
                _s1mpl3Flag = 0;
            }
        }
    

}

#pragma mark-- 点击手势

-(void)loveTapAction{
    //查询
    NSArray *array = [NSArray array];
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Focus"];
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", @"一菲"];
    //    [fetchRequest setPredicate:predicate];
//    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
//    [fetchRequest setSortDescriptors:@[sortDescriptor]];
    array = [_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
//    for (Focus *s in array) {
//        NSLog(@"%@", s);
//    }
    for (Focus *s in array) {
        if ([s.iD isEqualToString:[NSString stringWithFormat:@"%@", _str]]) {
            [_manager.managedObjectContext deleteObject:s];
            [_manager saveContext];
            _s1mpl3HeadView.loveLabel.text = @"收藏";
            return;
        }
    }
    //添加
    Focus *focus = [NSEntityDescription insertNewObjectForEntityForName:@"Focus" inManagedObjectContext:_manager.managedObjectContext];
    focus.albumCoverUrl290 = _moreRecommend.albumCoverUrl290;
    focus.albumId = [NSString stringWithFormat:@"%@", _moreRecommend.albumId];
    focus.coverMiddle = _moreRecommend.coverMiddle;
    focus.intro = _moreRecommend.intro;
    focus.iD = [NSString stringWithFormat:@"%@", _moreRecommend.ID];
    focus.isFinished = [NSString stringWithFormat:@"%@", _moreRecommend.isFinished];
    focus.lastUptrackAt = [NSString stringWithFormat:@"%@", _moreRecommend.lastUptrackAt];
    focus.lastUptrackId = [NSString stringWithFormat:@"%@", _moreRecommend.lastUptrackId];
    focus.lastUptrackTitle = _moreRecommend.lastUptrackTitle;
    focus.nickname = _moreRecommend.nickname;
    focus.playsCounts = [NSString stringWithFormat:@"%@", _moreRecommend.playsCounts];
    focus.serialState = [NSString stringWithFormat:@"%@", _moreRecommend.serialState];
    focus.tags = _moreRecommend.tags;
    focus.title = _moreRecommend.title;
    focus.tracks = [NSString stringWithFormat:@"%@", _moreRecommend.tracks];
    focus.tracksCounts = [NSString stringWithFormat:@"%@", _moreRecommend.tracksCounts];
    focus.uid = [NSString stringWithFormat:@"%@", _moreRecommend.uid];
    _s1mpl3HeadView.loveLabel.text = @"已收藏";
    _s1mpl3HeadView.loveImageView.image = [UIImage imageNamed:@""];
    [_manager saveContext];
}

-(void)aboutTapAction{
    S1mpl3AboutViewController *s1mpl3AboutVC = [[S1mpl3AboutViewController alloc] init];
    s1mpl3AboutVC.albumNum = _albumId;
    [self.navigationController pushViewController:s1mpl3AboutVC animated:YES];
}

-(void)moreTapAction{
    S1mpl3MoreInfoViewController *moreInfoVC = [[S1mpl3MoreInfoViewController alloc] init];
    moreInfoVC.dataSourceDic = _albumDic;
    [self.navigationController pushViewController:moreInfoVC animated:YES];
}

-(void)headTapAction{
    S1mpl3HeadInfoViewController *headInfoVC = [[S1mpl3HeadInfoViewController alloc] init];
    headInfoVC.s1mpl3HeadDataSourceDic = _albumDic;
    [self.navigationController pushViewController:headInfoVC animated:YES];
}

-(void)sortTapAction:(UITapGestureRecognizer *)tap{
    S1mpl3TableViewHeadView *headView = [_headViewsArray lastObject];
    _dataSourceArray = (NSMutableArray *)[[_dataSourceArray reverseObjectEnumerator] allObjects];
//    [_tableView reloadData];
    [UIView animateWithDuration:.3 animations:^{
        headView.sortImageView.transform = CGAffineTransformRotate(headView.sortImageView.transform, M_PI);
    }];
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 0; i < _dataSourceArray.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [array addObject:indexPath];
    }
    [_tableView reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationAutomatic];

}

#pragma mark--scrollView代理方法

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_imageView removeFromSuperview];
//    NSLog(@"%@", NSStringFromCGPoint(scrollView.contentOffset));
    if (scrollView.contentOffset.y > 185 * FITHeight) {
        _imageView = [[UIImageView alloc] init];
        _imageView.frame = CGRectMake(0, -280 * FITWidth, _s1mpl3HeadView.backImageView.frame.size.width, _s1mpl3HeadView.backImageView.frame.size.height);
//        [_s1mpl3HeadView removeFromSuperview];
        _imageView.image = _s1mpl3HeadView.backImageView.image;
        _imageView.alpha = 1;
        [self.view addSubview:_imageView];
    }else{
        [_imageView removeFromSuperview];
        _imageView = nil;
//        _tableView.tableHeaderView = _s1mpl3HeadView;
    }
    
    
}


#pragma mark--tableView代理方法


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _num;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40 * FITHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

        S1mpl3TableViewHeadView *headView = [[S1mpl3TableViewHeadView alloc] initWithFrame:CGRectMake(0, 0, 375 * FITWidth, 40 * FITHeight)];
        [_headViewsArray addObject:headView];
//        NSLog(@"a---%@", headView);
        headView.totalLabel.text = [NSString stringWithFormat:@"共%@集", _totalString];
        
        headView.sortLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *sortTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sortTapAction:)];
    
        [headView.sortLabel addGestureRecognizer:sortTap];
        
        headView.sortImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *sortTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sortTapAction:)];
    [headView.sortImageView addGestureRecognizer:sortTap1];
    
    return headView;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    S1mpl3AlbumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[S1mpl3AlbumTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    cell.dic = [_dataSourceArray objectAtIndex:indexPath.row];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130 * FITHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSourceArray.count;
}

#pragma mark - 点击跳转到播放界面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_dataSourceArray.count == 0) {
        return;
    }
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LZPlayViewController shareInstance]];
    [LZPlayViewController shareInstance].dataArray = _LZarray;
    [LZPlayViewController shareInstance].dicArray = _dataSourceArray;
    [LZPlayViewController shareInstance].index = indexPath.row;
    [LZPlayViewController shareInstance].dic = _dataSourceArray[indexPath.row];

    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"cell0"];
    [self presentViewController:nav animated:YES completion:nil];
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //2.找到document文件夹
    NSString *documents = [array lastObject];
    //3.拼接要存放数组的文件路径
    NSString *documentPath = [documents stringByAppendingPathComponent:@"zbbCace"];
    NSArray *dicArray = (NSArray *)_dataSourceArray;
    [[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:@"index"];
     NSDictionary *dic = _dataSourceArray[indexPath.row];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:dicArray, @"dicArray", dic, @"dic", nil];
    [dictionary writeToFile:documentPath atomically:YES];
    [TabBarController shareInstance].playButton.alpha = 0;
    [TabBarController shareInstance].flagInit = 0;
    [[TabBarController shareInstance].imageView sd_setImageWithURL:[NSURL URLWithString:[_dataSourceArray[indexPath.row] objectForKey:@"albumImage"]]];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
